const fs = require("fs");
const request = require("request");
const schedule = require('node-schedule');
const configJson = require('./config.json');
const nodemailer = require("nodemailer");

const user = '617829754@qq.com'

const transporter = nodemailer.createTransport({
    host: "smtp.qq.com",
    port: 465,
    secure: true, // true for 465, false for other ports
    // service: "SendGrid",
    auth: {
        user,
        pass: 'geyegotthayibffe'
    }
});

/**
 * 获取当前公网ip
 * @returns {String} ip
 */
const getPublicIP = () => {
    let url = 'https://qifu-api.baidubce.com/ip/local/geo/v1/district';
    return new Promise((resolve, reject) => {
        request(url, function (e, res) {
            let ip = res && res.body ? res.body.match(/(?:\d+\.){3}\d+/)[0] : ''
            console.log('ip',ip)
            resolve(ip)
            if (e) reject(e)
        })
    })
}

const sendEmail = (ip) => {
    const mailOptions = {
        to: "331084293@qq.com",
        from: `617829754<${user}>`,
        subject: "ip变更",
        text: ip.toString()
    };

    transporter.sendMail(mailOptions, (err) => {
        if (err) {
           return console.log('err', err)
        }
        console.log('邮件发送成功')
    });
};

const main = async () => {
    let ip = await getPublicIP()
    if ((ip && ip === configJson.ip) || !ip) return
    // 写入配置文件
    configJson.ip = ip
    fs.writeFileSync('./config.json', JSON.stringify(configJson))
    sendEmail(ip)
}

//生产环境启用ddns
schedule.scheduleJob('*/10 * * * *', () => {
    if (configJson.ip) {
        main()
    }
});